﻿import { HttpException, HttpStatus, Injectable, NotAcceptableException } from '@nestjs/common';
import { OrderService } from 'src/order/order.service';
import { ProductService } from 'src/product/product.service';
import { UtilsService } from 'src/utils/utils.service';
import { AliConfig } from './ali.config';
@Injectable()
export class PayService {

    constructor(
        private readonly utilService: UtilsService
    ) { }

    //小程序下单
    async placeAnOrder(query: any, orderService: OrderService) {
        const order = await orderService.verifyOrCreateOrder({
            product: query.product,
            user_id: query.user.user_id
        });
        // 订单为未支付状态则吊起支付，否侧返回已支付的订单
        if (order.pay_state !== 'NOTPAY') {
            return {
                pay_state_desc: order.pay_state_desc,
                pay_state: order.pay_state,
                pay_method: order.pay_method,
                id: order.id,
                order_number: order.order_number,
                product_name: order.product_name
            };
        }
        //appid:wxdc5881a7a5462f77
        //AppSecret:3ac4be37a5ab66ddcfff9afb0df61ca3
        //mchid:1628971413
        //APIv3:GIc55X7OmWp6IS470c10m25gkadZUvCd
        const { openid } = query;
        const requestBody = {
            appid: 'wxdc5881a7a5462f77',//小程序appid
            mchid: '1628971413',//商户号id
            description: order.product_name,//商品描述
            out_trade_no: order.order_number,//订单号
            notify_url: 'https://bangkeedu.com:3000/payNotice',//处理支付通知回调地址
            amount: {
                total: order.buy_price * 100, //总金额：单位/分
                currency: 'CNY'//货币类型 CNY：人民币
            },
            payer: {
                openid//支付者
            }
        }
        //返回 预支付交易会话标识：prepay_id用于后续接口调用中使用，该值有效期为2小时
        const { prepay_id } = await this.utilService.getWechatSign('POST', '/v3/pay/transactions/jsapi', requestBody);
        const timeStamp = (Date.parse(new Date().toString()) / 1000).toString();
        const nonceStr = this.utilService.randomString();
        return {
            timeStamp,
            nonceStr,
            package: `prepay_id=${prepay_id}`,
            signType: "RSA",
            paySign: await this.utilService.paySign(timeStamp, nonceStr, prepay_id),
            orderNumber: order.order_number
        };
    }

    async index(body: any, orderService: OrderService) {
        const order = await orderService.verifyOrCreateOrder({
            product: body?.product,
            order_number: body?.order_number,
            user_id: body.user.user_id
        });
        // 订单为未支付状态则吊起支付，否侧返回已支付的订单
        if (order.pay_state === 'NOTPAY') {
            return await this.pay(body.pay_method, {
                out_trade_no: order.order_number,
                description: order.product_name,
                total_amount: order.buy_price
            })
        } else {
            return {
                pay_state_desc: order.pay_state_desc,
                pay_state: order.pay_state,
                pay_method: order.pay_method,
                id: order.id,
                order_number: order.order_number,
                product_name: order.product_name
            };
        }
    }
    async pay(method: 'wechat' | 'ali', options: {
        out_trade_no: string,
        description: string,
        total_amount: number
    }) {
        if (method === 'wechat') {
            const requestBody = {
                appid: "wxdc5881a7a5462f77",//应用id
                mchid: "1628971413",//商户号id
                out_trade_no: options.out_trade_no,//订单号
                description: options.description,//商品描述
                notify_url: "https://bangkeedu.com:3000/payNotice",//通知地址
                amount: {
                    total: options.total_amount * 100,//支付总金额分单位
                    currency: "CNY"
                }
            };
            return {
                pay: await this.utilService.getWechatSign('POST', '/v3/pay/transactions/native', requestBody),//返回微信支付协议用于生成支付二维码
                order_number: options.out_trade_no
            }
        }
        if (method === 'ali') {
            const alipay = new AliConfig();
            return {
                pay: await alipay.pagePay({
                    outTradeNo: options.out_trade_no,
                    totalAmount: options.total_amount,
                    subject: options.description
                }),
                order_number: options.out_trade_no
            };
        }
    }
}
